const multer = require('multer')
const path = require('path')
const fs = require('fs')

// 设置文件存储路径和文件名
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    let targetDir
    // 根据请求的URL或其它条件选择目标目录,先判断文件夹是否存在不存在就新建

    console.log(req.url)
    if (req.url === '/uploadCarousel') {
      if (!fs.existsSync(path.join(__dirname, '../uploads/carousel/'))) {
        fs.mkdirSync(path.join(__dirname, '../uploads/carousel/'))
      }
      targetDir = path.join(__dirname, '../uploads/carousel/')
    } else {
      // 默认目录
      if (!fs.existsSync(path.join(__dirname, '../uploads/others/'))) {
        fs.mkdirSync(path.join(__dirname, '../uploads/others/'))
      }
      targetDir = path.join(__dirname, '../uploads/others/')
    }

    cb(null, targetDir)
  },
  filename: function (req, file, cb) {
    cb(null, `${Date.now()}-${file.originalname}`)
  }
})

// 文件类型过滤
const fileFilter = (req, file, cb) => {
  console.log('[文件类型检测] 文件名:', file.originalname)
  console.log('[文件类型检测] 客户端报告类型:', file.mimetype)
  console.log('[文件类型检测] 文件类型:', file)
  const fileSplit = file.originalname.split('.')
  const fileType = fileSplit[fileSplit.length - 1]
  const allowedTypes = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']
  if (allowedTypes.includes(fileType)) {
    console.log('[通过] 文件类型验证成功')
    cb(null, true)
  } else {
    console.log('[拒绝] 非图片文件类型:', fileType)
    cb(new Error('仅允许上传图片文件'), false)
  }
}

// 初始化multer
const upload = multer({
  storage: storage,
  limits: {
    fileSize: 10 * 1024 * 1024, // 10MB
    files: 5
  },
  fileFilter: fileFilter
})

module.exports = upload
